package com.tingyukeji.fastpay.ui.fragment;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.tingyukeji.fastpay.R;
import com.tingyukeji.fastpay.adapter.CommuityAdapter;
import com.tingyukeji.fastpay.adapter.VideoAdapter;
import com.tingyukeji.fastpay.base.BaseFragment;
import com.tingyukeji.fastpay.base.BaseRecyclerAdapter;
import com.tingyukeji.fastpay.collection.activity.CollectionActivity;
import com.tingyukeji.fastpay.databinding.CenterFragmentBinding;
import com.tingyukeji.fastpay.entity.BaseReqEntity;
import com.tingyukeji.fastpay.entity.HomePageEntity;
import com.tingyukeji.fastpay.entity.ReqCompletedLisener;
import com.tingyukeji.fastpay.login.ui.activity.LoginActivity;
import com.tingyukeji.fastpay.message.activity.MessageActivity;
import com.tingyukeji.fastpay.shop.activity.ShopDetailActivity;
import com.tingyukeji.fastpay.user.activity.BusinessRegistrationBankActivity;
import com.tingyukeji.fastpay.utils.SharedPreferencesUtils;
import com.tingyukeji.fastpay.view.MyGridLayoutManager;
import com.tingyukeji.fastpay.view.ZQImageViewRoundOval;
import com.tingyukeji.fastpay.view.bannerview.MZBannerView;
import com.tingyukeji.fastpay.view.bannerview.holder.MZHolderCreator;
import com.tingyukeji.fastpay.view.bannerview.holder.MZViewHolder;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/5/31.
 */

public class CenterFragment extends BaseFragment {
    public static final String TAG = "CenterFragment";
    private CenterFragmentBinding binding;
    private MZBannerView mMZBanner;
//    public static final int[] BANNER = new int[]{R.mipmap.banner1, R.mipmap.banner2, R.mipmap.banner3, R.mipmap.banner4, R.mipmap.banner5};
    private SharedPreferencesUtils sp;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == rootView) {
            binding = DataBindingUtil.inflate(inflater, R.layout.center_fragment,container, false);
            rootView = binding.getRoot();
            initView();
        } else {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }
        return rootView;
    }

    @Override
    protected void initView() {
        super.initView();
        sp = new SharedPreferencesUtils(getActivity());
        binding.llMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goActivity(MessageActivity.class);
            }
        });
//        initBanner();
//        initCommun();
//        initOnlineStore();
        inData();
    }

    private void inData() {
        String token = (String) sp.getParam("TOKEN","");
        if (!TextUtils.isEmpty(token)){
            BaseReqEntity homePageEntity = new HomePageEntity()
                    .putParam("token",token)
                    .setReqType(BaseReqEntity.POST)
                    .setLisener(new ReqCompletedLisener<HomePageEntity>() {
                        @Override
                        public void notifyReqCompleted(boolean success, HomePageEntity data, String errMsg, boolean isCacheOpen) {
                            if (null != data) {
                                Toast.makeText(getActivity(),data.message,Toast.LENGTH_SHORT).show();
                                if (data.code == 1 && data.successful && null != data.getData() && null != data.getData().data){
                                    for (int i = 0; i < data.getData().data.size(); i++){
                                        if (null != data.getData().data.get(i).panelContents && data.getData().data.get(i).panelContents.size() > 0){
                                            if (data.getData().data.get(i).type == 0){
                                                initBanner(data.getData().data.get(i).panelContents);
                                            }else if (data.getData().data.get(i).type == 1){
                                                initCommun(data.getData().data.get(i).panelContents);
                                            }else if (data.getData().data.get(i).type == 2){
                                                initNews(data.getData().data.get(i).panelContents);
                                            }else if (data.getData().data.get(i).type == 3){
                                                initService(data.getData().data.get(i).panelContents);
                                            }else if (data.getData().data.get(i).type == 4){
                                                initOnlineStore(data.getData().data.get(i).panelContents);
                                            }
                                        }
                                    }
                                }else if (data.code == 10001002){
                                    goActivity(LoginActivity.class);
                                }
                            }else {
                                Toast.makeText(getActivity(),"请求失败！",Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
            homePageEntity.execute();
        }else {
            goActivity(LoginActivity.class);
        }
    }

    private void initService(List<HomePageEntity.PanelContent> panelContents) {
        if (panelContents.size() >= 4){
            binding.tvFeaturesTitleOne.setText(panelContents.get(0).productName);
            binding.tvFeaturesSubTitleOne.setText(panelContents.get(0).subTitle);
            Glide.with(context)
                    .load(panelContents.get(0).picUrl)
                    .placeholder(R.mipmap.ic_service)//图片加载出来前，显示的图片
                    .error(R.mipmap.ic_service)//图片加载失败后，显示的图片
                    .into(binding.featuresOne);
            binding.tvFeaturesTitleTwo.setText(panelContents.get(1).productName);
            binding.tvFeaturesSubTitleTwo.setText(panelContents.get(1).subTitle);
            Glide.with(context)
                    .load(panelContents.get(1).picUrl)
                    .placeholder(R.mipmap.ic_service)//图片加载出来前，显示的图片
                    .error(R.mipmap.ic_service)//图片加载失败后，显示的图片
                    .into(binding.featuresTwo);
            binding.tvFeaturesTitleThree.setText(panelContents.get(2).productName);
            binding.tvFeaturesSubTitleThree.setText(panelContents.get(2).subTitle);
            Glide.with(context)
                    .load(panelContents.get(2).picUrl)
                    .placeholder(R.mipmap.ic_service)//图片加载出来前，显示的图片
                    .error(R.mipmap.ic_service)//图片加载失败后，显示的图片
                    .into(binding.featuresThree);
            binding.tvFeaturesTitleFour.setText(panelContents.get(3).productName);
            binding.tvFeaturesSubTitleFour.setText(panelContents.get(3).subTitle);
            Glide.with(context)
                    .load(panelContents.get(3).picUrl)
                    .placeholder(R.mipmap.ic_service)//图片加载出来前，显示的图片
                    .error(R.mipmap.ic_service)//图片加载失败后，显示的图片
                    .into(binding.featuresFour);
            binding.rlFeaturesOne.setVisibility(View.VISIBLE);
            binding.rlFeaturesTwo.setVisibility(View.VISIBLE);
            binding.rlFeaturesThree.setVisibility(View.VISIBLE);
            binding.rlFeaturesFour.setVisibility(View.VISIBLE);
        }else if (panelContents.size() >= 3){
            binding.tvFeaturesTitleOne.setText(panelContents.get(0).productName);
            binding.tvFeaturesSubTitleOne.setText(panelContents.get(0).subTitle);
            Glide.with(context)
                    .load(panelContents.get(0).picUrl)
                    .placeholder(R.mipmap.ic_service)//图片加载出来前，显示的图片
                    .error(R.mipmap.ic_service)//图片加载失败后，显示的图片
                    .into(binding.featuresOne);
            binding.tvFeaturesTitleTwo.setText(panelContents.get(1).productName);
            binding.tvFeaturesSubTitleTwo.setText(panelContents.get(1).subTitle);
            Glide.with(context)
                    .load(panelContents.get(1).picUrl)
                    .placeholder(R.mipmap.ic_service)//图片加载出来前，显示的图片
                    .error(R.mipmap.ic_service)//图片加载失败后，显示的图片
                    .into(binding.featuresTwo);
            binding.tvFeaturesTitleThree.setText(panelContents.get(2).productName);
            binding.tvFeaturesSubTitleThree.setText(panelContents.get(2).subTitle);
            Glide.with(context)
                    .load(panelContents.get(2).picUrl)
                    .placeholder(R.mipmap.ic_service)//图片加载出来前，显示的图片
                    .error(R.mipmap.ic_service)//图片加载失败后，显示的图片
                    .into(binding.featuresThree);
            binding.rlFeaturesOne.setVisibility(View.VISIBLE);
            binding.rlFeaturesTwo.setVisibility(View.VISIBLE);
            binding.rlFeaturesThree.setVisibility(View.VISIBLE);
            binding.rlFeaturesFour.setVisibility(View.INVISIBLE);
        }else if (panelContents.size() >= 2){
            binding.tvFeaturesTitleOne.setText(panelContents.get(0).productName);
            binding.tvFeaturesSubTitleOne.setText(panelContents.get(0).subTitle);
            Glide.with(context)
                    .load(panelContents.get(0).picUrl)
                    .placeholder(R.mipmap.ic_service)//图片加载出来前，显示的图片
                    .error(R.mipmap.ic_service)//图片加载失败后，显示的图片
                    .into(binding.featuresOne);
            binding.tvFeaturesTitleTwo.setText(panelContents.get(1).productName);
            binding.tvFeaturesSubTitleTwo.setText(panelContents.get(1).subTitle);
            Glide.with(context)
                    .load(panelContents.get(1).picUrl)
                    .placeholder(R.mipmap.ic_service)//图片加载出来前，显示的图片
                    .error(R.mipmap.ic_service)//图片加载失败后，显示的图片
                    .into(binding.featuresTwo);
            binding.rlFeaturesOne.setVisibility(View.VISIBLE);
            binding.rlFeaturesTwo.setVisibility(View.VISIBLE);
            binding.rlFeaturesThree.setVisibility(View.INVISIBLE);
            binding.rlFeaturesFour.setVisibility(View.INVISIBLE);
        }else if (panelContents.size() >= 1){
            binding.tvFeaturesTitleOne.setText(panelContents.get(0).productName);
            binding.tvFeaturesSubTitleOne.setText(panelContents.get(0).subTitle);
            Glide.with(context)
                    .load(panelContents.get(0).picUrl)
                    .placeholder(R.mipmap.ic_service)//图片加载出来前，显示的图片
                    .error(R.mipmap.ic_service)//图片加载失败后，显示的图片
                    .into(binding.featuresOne);
            binding.rlFeaturesOne.setVisibility(View.VISIBLE);
            binding.rlFeaturesTwo.setVisibility(View.INVISIBLE);
            binding.rlFeaturesThree.setVisibility(View.INVISIBLE);
            binding.rlFeaturesFour.setVisibility(View.INVISIBLE);
        }
    }

    private void initNews(List<HomePageEntity.PanelContent> panelContents) {
        if (panelContents.size()>=2){
            binding.tvNewsOne.setText(panelContents.get(0).productName);
            binding.tvNewsTwo.setText(panelContents.get(1).productName);
            binding.tvNewsOne.setVisibility(View.VISIBLE);
            binding.tvNewsTwo.setVisibility(View.VISIBLE);
        }else if (panelContents.size()>=1){
            binding.tvNewsOne.setText(panelContents.get(0).productName);
            binding.tvNewsOne.setVisibility(View.VISIBLE);
            binding.tvNewsTwo.setVisibility(View.GONE);
        }
    }

    private void initOnlineStore(List<HomePageEntity.PanelContent> panelContents) {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(),1,GridLayoutManager.VERTICAL,false){
            @Override
            public boolean canScrollVertically() {
                // 直接禁止垂直滑动
                return false;
            }
        };
        binding.onlineStoreRecyclerview.setLayoutManager(gridLayoutManager); //给RecyClerView 添加设置好的布局样式
        VideoAdapter videoAdapter = new VideoAdapter(panelContents,context,false); //初始化适配器
        binding.onlineStoreRecyclerview.setAdapter(videoAdapter); // 对 recyclerview 添加数据内容
        videoAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int pos) {
                goActivity(ShopDetailActivity.class);
            }
        });
    }

    private void initCommun(List<HomePageEntity.PanelContent> panelContents) {
        MyGridLayoutManager gridLayoutManager = new MyGridLayoutManager(getActivity(),4,GridLayoutManager.VERTICAL,false);
        gridLayoutManager.setScrollEnabled(false);
        binding.communityRecyclerview.setLayoutManager(gridLayoutManager); //给RecyClerView 添加设置好的布局样式
        CommuityAdapter commuityAdapter = new CommuityAdapter(panelContents,context,false); //初始化适配器
        binding.communityRecyclerview.setAdapter(commuityAdapter); // 对 recyclerview 添加数据内容
        commuityAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int pos) {
                if (pos == 0){
                    goActivity(CollectionActivity.class);
                }else {
                    goActivity(BusinessRegistrationBankActivity.class);
                }
            }
        });
    }

    private void initBanner( List<HomePageEntity.PanelContent> panelContents) {
        mMZBanner = (MZBannerView) binding.banner;
        mMZBanner.setBannerPageClickListener(new MZBannerView.BannerPageClickListener() {
            @Override
            public void onPageClick(View view, int position) {
                Toast.makeText(getContext(), "click page:" + position, Toast.LENGTH_LONG).show();
            }
        });
        mMZBanner.addPageChangeLisnter(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                Log.e(TAG, "----->addPageChangeLisnter:" + position + "positionOffset:" + positionOffset + "positionOffsetPixels:" + positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                Log.e(TAG, "addPageChangeLisnter:" + position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        List<String> bannerList = new ArrayList<>();
        for (int i = 0; i < panelContents.size(); i++) {
            bannerList.add(panelContents.get(i).picUrl);
        }
        mMZBanner.setIndicatorVisible(true);

        mMZBanner.setPages(bannerList, new MZHolderCreator<BannerViewHolder>() {
            @Override
            public BannerViewHolder createViewHolder() {
                return new BannerViewHolder();
            }
        });
        mMZBanner.start();
    }

    public static class BannerViewHolder implements MZViewHolder<String> {
        private ZQImageViewRoundOval mImageView;

        @Override
        public View createView(Context context) {
            // 返回页面布局文件
            View view = LayoutInflater.from(context).inflate(R.layout.banner_item, null);
            mImageView = (ZQImageViewRoundOval) view.findViewById(R.id.banner_image);
            mImageView.setType(ZQImageViewRoundOval.TYPE_ROUND);
            mImageView.setRoundRadius(30);
            return view;
        }

        @Override
        public void onBind(Context context, int position, String data) {
            // 数据绑定
            //属性的配置
            /*RequestOptions options = new RequestOptions()
                    //加载成功之前占位图
                    .placeholder(R.mipmap.ic_launcher)
                    //加载错误之后的错误图
                    .error(R.mipmap.ic_launcher)
                    //跳过内存缓存
                    .skipMemoryCache(true)
                    //跳过磁盘缓存
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .priority(Priority.HIGH);
            Glide.with(context)
                    .load(data).apply(options).listener(new RequestListener<Drawable>() {
                @Override
                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                    Log.d("menu_glidefailed",e.toString());
                    return false;
                }

                @Override
                public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                    return false;
                }
            }) //加载地址
                    .into(mImageView);//显示的位置*/

            Glide.with(context)
                    .load(data)
                    .placeholder(R.mipmap.banner1)//图片加载出来前，显示的图片
                    .error(R.mipmap.banner1)//图片加载失败后，显示的图片
                    .into(mImageView);

//            mImageView.setImageResource(data);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (null != mMZBanner){
            mMZBanner.pause();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (null != mMZBanner){
            mMZBanner.start();
        }
    }
}
